import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns = {"/login"})
public class login extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
	String URL=(String)getServletContext().getInitParameter("db.url");
	String NAME=(String)getServletContext().getInitParameter("db.user");
	String PASSWORD=(String)getServletContext().getInitParameter("db.password");
	System.out.println(res.isCommitted());
	try (Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD)) {
	    String sqlQuery = "select username,familyname, name, email, passwd from user where username='"+req.getParameter("username")+"'";
	    System.out.println(sqlQuery);
	    Statement sqlStmt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);

	    ResultSet rs=sqlStmt.executeQuery("select * from user where username='"+req.getParameter("username")+"'");
	    rs.next();
	    System.out.println(rs.getString("username")+rs.getString("name"));

	    sqlStmt.executeQuery(sqlQuery);
	    ResultSet sqlResultSet = sqlStmt.getResultSet();
	    sqlResultSet.next();
	    System.out.println(res.isCommitted());
	    Map<String, String> message = new LinkedHashMap<String, String>();
	    message.put("用户名",sqlResultSet.getString("username"));
	    message.put("姓",sqlResultSet.getString("familyname"));
	    message.put("名",sqlResultSet.getString("name"));
	    message.put("邮箱",sqlResultSet.getString("email"));
	    HttpSession session = req.getSession(true);
	    if(req.getParameter("net_auto_login") != null)
		session.setMaxInactiveInterval(7*24*60*60);
	    session.setAttribute("Login", message);
	    session.setAttribute("username", sqlResultSet.getString("username"));
	    res.sendRedirect("http://localhost:8080/profile.jsp");
	}catch (SQLException e){
	    e.printStackTrace();
	}
    }
}
